<?php
/*
 * Copyright 2010 Johannes M. Schmitt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

class closureCompiletemplatesTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      // add your own options here
    ));

    $this->namespace        = 'closure';
    $this->name             = 'compile-templates';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [closure:compile-templates|INFO] task compiles all your Google Closure templates.
Call it with:

  [php symfony closure:compile-templates|INFO]
EOF;
  }

  protected function execute($arguments = array(), $options = array())
  {
    $webDir = sfConfig::get('sf_web_dir');
    $soyFiles = sfFinder::type('file')
    			->name('*.soy')
    			->in($webDir);
   	
    foreach ($soyFiles as $soyFile)
    {
    	$compiler = new GoogleClosureTemplateCompiler(file_get_contents($soyFile));
    	$baseName = basename($soyFile, '.soy');

    	$code = $compiler->getCompiledCode();
    	if ($compiler->hasError() === false)
    	{
			$code = preg_replace('#^([^\n]*\n){2}#', '', $code);
			$code = "/**
 * This file has been automatically generated from ".$soyFile.".
 * Do NOT edit it manually.
 *
 * Command: ".$compiler->getCommand()."
 */
".$code;    	
    	}
    	
    	$compiledFile = dirname($soyFile).'/'.$baseName.'.js';
    	file_put_contents($compiledFile, $code);
    	$this->logSection('file+', $compiledFile);
    }
  }
}
